package com.tanhua.sso.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SmsUtil {

    /**
     * 发送验证码短信
     *
     * @param mobile 目标手机号
     * @param length 要发送的验证码的位数
     * @param aliyunSMSConfig aliyun配置文件
     * @return 发送成功:验证码;发送失败:null
     */
    public String sendSms(String mobile, Integer length, AliyunSMSConfig aliyunSMSConfig) {/*sendSms()是阿里云短信业务提供的代码,不必理解.*/
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSMSConfig.getRegionId(),
                aliyunSMSConfig.getAccessKeyId(), aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";//生成随机的6位验证码

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);//目标手机号
        request.putQueryParameter("SignName", aliyunSMSConfig.getSignName());//签名名称
        request.putQueryParameter("TemplateCode", aliyunSMSConfig.getTemplateCode());//短信模版code
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模版中变量替换
        try {
            //CommonResponse response = client.getCommonResponse(request);
            //String data = response.getData();

            // 假定发送成功
            String data = "\"Message\":\"OK\"";
            //String data = "";//假定发送失败

            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                //return code;//返回一个随机6位验证码
                return "123456";
            }
            log.info("阿里云验证码短信发送失败---data : " + data);
        } catch (Exception e) {
            log.error("阿里云验证码短信发送失败---mobile : " + mobile, e);
        }
        return null;
    }
}
